package com.vogue.supplymall.match.domain.service.impl;

import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.account.domain.model.Address;
import com.vogue.supplymall.account.domain.model.RelUserCode;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.AddressService;
import com.vogue.supplymall.account.domain.service.BaseCodeService;
import com.vogue.supplymall.account.domain.service.BaseRegistinfoService;
import com.vogue.supplymall.account.domain.service.RelUserCodeService;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.account.shiro.bean.PasswordBean;
import com.vogue.supplymall.admin.business.domain.model.AdminPlatform;
import com.vogue.supplymall.admin.business.domain.service.AdminPlatformService;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.SearchInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.match.domain.dao.MatchOrganDao;
import com.vogue.supplymall.match.domain.dto.*;
import com.vogue.supplymall.match.domain.model.MatchOrgan;
import com.vogue.supplymall.match.domain.model.RelUserOrgan;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.match.domain.service.RelUserOrganService;
import com.vogue.supplymall.shop.domain.model.OrganShopImg;
import com.vogue.supplymall.shop.domain.model.RelShopCategory;
import com.vogue.supplymall.shop.domain.model.Shop;
import com.vogue.supplymall.shop.domain.service.OrganShopImgService;
import com.vogue.supplymall.shop.domain.service.RelShopCategoryService;
import com.vogue.supplymall.shop.domain.service.ShopService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Service("matchOrganService")
@Transactional
public class MatchOrganServiceImpl extends BaseServiceImpl<MatchOrgan, Long> implements MatchOrganService {
    @Resource
    private OrganShopImgService organShopImgService;
    @Resource
    private MatchOrganDao matchOrganDao;
    @Resource
    private ShopService shopService;
    @Resource
    private AddressService addressService;
    @Resource
    private UserService userService;
    @Resource
    private RelUserOrganService relUserOrganService;
    @Resource
    private RelShopCategoryService relShopCategoryService;
    @Resource
    private BaseCodeService baseCodeService;
    @Resource
    private MessageSourceUtils messageSourceUtils;
    @Resource
    private BaseRegistinfoService baseRegistinfoService;
    @Resource
    private RelUserCodeService relUserCodeService;
    @Resource
    private AdminPlatformService adminPlatformService;

    Locale locale = LocaleContextHolder.getLocale();
    private static final String defaultPwd="111111";

    public MatchOrganServiceImpl(BaseDao<MatchOrgan, Long> baseDao) {
        super(baseDao);
        matchOrganDao = (MatchOrganDao) baseDao;
    }

    @Override
    public Map<String, Object> matchEnterprise(BaseDTO<EnterpriseDTO> baseDTO) throws Exception {
        if (baseDTO != null && baseDTO.getData() != null) {
        	boolean disableFlag=false;
            Long sysCodeId = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());

            EnterpriseDTO enterpriseDTO = baseDTO.getData();
            String matchId = enterpriseDTO.getMatchid();
            MatchOrgan matchOrgan = matchOrganDao.getEnterpriseByMatchId(sysCodeId);

            //判断是否在别的平台店铺已审核通过
            DealStatus.kacha();
            MatchOrgan mo=matchOrganDao.getMatchOrganByMatchId(sysCodeId, matchId);
            
            if(mo==null) {	
            	disableFlag=true;
            }else {
            	disableFlag=mo.isDisabledflag();
            }
            
            if (matchOrgan != null) {//update
                updateEnterprise(matchOrgan, enterpriseDTO, sysCodeId,disableFlag);
            } else {//add
                saveEnterprise(matchOrgan, enterpriseDTO, sysCodeId,disableFlag);
            }


        }
        return null;
    }

    private void saveEnterprise(MatchOrgan matchOrgan, EnterpriseDTO enterpriseDTO, Long sysCodeId,boolean disableFlag) throws Exception {

        //新增matchOrgan
        matchOrgan = new MatchOrgan();
        matchOrgan.setDisabledflag(disableFlag);
        this.saveOrUpdateEnterpriseMarchOrgan(matchOrgan, enterpriseDTO, sysCodeId, "add");

        //更新该企业下相关门店 是否等待手动接单 的标记
        shopService.updateWaitingOrderBySyscodeId(sysCodeId, enterpriseDTO.getWaitingOrder());

        //更新base_code的tpsystem列
  		int tpsystem=enterpriseDTO.getTpsystem();
  		baseCodeService.updateTpsystemBySyscodeId(sysCodeId, tpsystem);
        
        //保存上传的图片，如果没有上传图片，插入空值，前端取默认图片
        this.saveOrganShopImg(enterpriseDTO.getImg(), matchOrgan.getId(), sysCodeId,0);

        //店铺与分类对应关系新增
        this.saveEnterpriseCategoryids(enterpriseDTO.getCategoryids().split(","), sysCodeId, matchOrgan.getId());

       //更新注册开通账号的名称（集团名或个人店名）
        baseRegistinfoService.insertRegistName(sysCodeId, enterpriseDTO.getOrgname());

    }

    private void updateEnterprise(MatchOrgan matchOrgan, EnterpriseDTO enterpriseDTO, Long sysCodeId,boolean disableFlag) throws Exception {
        String matchId = enterpriseDTO.getMatchid();
        matchOrgan.setDisabledflag(disableFlag);
        
        //如果企业名称有更新，同步更新门店表的企业名称列
        if(!matchOrgan.getOrgname().equals(enterpriseDTO.getOrgname())) {
        	shopService.updateEntnameBySyscodeId(sysCodeId, enterpriseDTO.getOrgname());
        }
        
        //更新matchOrgan
        this.saveOrUpdateEnterpriseMarchOrgan(matchOrgan, enterpriseDTO, sysCodeId, "edit");

        //更新该企业下相关门店 是否等待手动接单 的标记
        shopService.updateWaitingOrderBySyscodeId(sysCodeId, enterpriseDTO.getWaitingOrder());

        //更新base_code的tpsystem列
  		int tpsystem=enterpriseDTO.getTpsystem();
  		baseCodeService.updateTpsystemBySyscodeId(sysCodeId, tpsystem);
        
        //更新上传的图片，先删后插
        matchOrganDao.deleteOrganShopImgByMatchId(matchId,sysCodeId);
        this.saveOrganShopImg(enterpriseDTO.getImg(), matchOrgan.getId(), sysCodeId,0);

        //更新店铺与分类对应关系，先删后插
        matchOrganDao.deleteRelShopCategoryBySysCodeId(sysCodeId);
        if (StringUtils.isNotBlank(enterpriseDTO.getCategoryids())) {
            this.saveEnterpriseCategoryids(enterpriseDTO.getCategoryids().split(","), sysCodeId, matchOrgan.getId());
        }
        
        //更新注册开通账号的名称（集团名或个人店名）
        baseRegistinfoService.insertRegistName(sysCodeId, enterpriseDTO.getOrgname());
    }

    /**
     * 新增或更新matchOrgan
     */
    public void saveOrUpdateEnterpriseMarchOrgan(MatchOrgan matchOrgan, EnterpriseDTO enterpriseDTO, Long sysCodeId, String oper) throws Exception {
        BeanUtils.copyProperties(matchOrgan, enterpriseDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(enterpriseDTO.getSign())) {
            matchOrgan.setSign("");
            ;
        }
        matchOrgan.setSyscodeid(sysCodeId);
        matchOrgan.setPid(0L);
        matchOrgan.setOrgname(enterpriseDTO.getOrgname());
        matchOrgan.setMatchid(enterpriseDTO.getMatchid());
        matchOrgan.setMcid("0");
        matchOrgan.setModifyDate(new Date());

        if (oper.equals("add")) {
            matchOrganDao.save(matchOrgan);
        } else if (oper.equals("edit")) {
            matchOrganDao.update(matchOrgan);
        }
    }

    /**
     * 保存机构图片
     */
    public void saveOrganShopImg(List<ImgDTO> imgDTOs, Long organId, Long sysCodeId,int organType) throws Exception {

        if (imgDTOs.size() > 0) {
        	
            for (ImgDTO img : imgDTOs) {
                OrganShopImg organShopImg = new OrganShopImg();

                //判断路径是否为空,为空设置路径为空串，前端给默认值
                if (StringUtils.isNotBlank(img.getImgurl())) {
                    organShopImg.setImgtype(img.getImgtype());
                    organShopImg.setImgurl(img.getImgurl());
                } else {
                    organShopImg.setImgtype(0);
                    organShopImg.setImgurl("");
                }

                organShopImg.setOrganid(organId);
                organShopImg.setSyscodeid(sysCodeId);
                organShopImg.setOrgantype(organType);

                organShopImgService.save(organShopImg);

                //目前仅支持一张图片，若支持多张，删除break即可
                break;
            }
        } else {
            OrganShopImg organShopImg = new OrganShopImg();
            organShopImg.setImgtype(0);
            organShopImg.setImgurl("");
            organShopImg.setOrganid(organId);
            organShopImg.setSyscodeid(sysCodeId);
            organShopImg.setOrgantype(organType);
            organShopImgService.save(organShopImg);
        }

    }

    /**
     * 保存店铺与分类对应关系
     */
    public void saveEnterpriseCategoryids(String[] categoryids, Long sysCodeId, Long organId) {
    	
        for (String categoryId : categoryids) {

            if (StringUtils.isNotEmpty(categoryId)) {
                RelShopCategory relShopCategory = new RelShopCategory();
                relShopCategory.setSyscodeid(sysCodeId);
                relShopCategory.setCategoryid(new Long(categoryId));
                relShopCategory.setSyscodeid(sysCodeId);
                relShopCategory.setOrganid(organId);

                relShopCategoryService.save(relShopCategory);
            }

        }
    }

    /**
     * 保存店铺资质上传的文字信息记录
     */
//	public void saveEnterpriseShopCert(Long sysCodeId) {
//		ShopCert sc=new ShopCert();
//		sc.setAddress("123");
//		sc.setCertinfo("1");
//		sc.setCheckflag(false);
//		sc.setMemo("0");
//		sc.setShopid(0L);
//		sc.setSyscodeid(sysCodeId);
//		shopCertService.save(sc);
//	}
    @Override
    public Map<String, Object> matchBuyerOrgan(BaseDTO<BuyerOrganDTO> baseDTO) throws Exception {
        if (baseDTO != null && baseDTO.getData() != null) {
        	boolean disableFlag=true;
        	
            Long sysCodeId = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());

            BuyerOrganDTO dataMap = baseDTO.getData();
            BuerEnterpriseDTO buerEnterpriseDTO = dataMap.getEnterprise();
            List<BuyerOrganDetailDTO> buyerOrganDetailDTOs = dataMap.getOrgan();

            //判断企业是否已存在，存在则更新企业信息，否则保存企业信息
            String enMatchId = buerEnterpriseDTO.getMatchid();
            MatchOrgan matchOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, enMatchId);
            if (matchOrgan != null) {//update
                matchOrgan.setModifyDate(new Date());
                matchOrgan.setOrgname(buerEnterpriseDTO.getOrgname());
                matchOrgan.setMcid("0");
                matchOrganDao.update(matchOrgan);
            } else {//add
                matchOrgan = new MatchOrgan();
                matchOrgan.setMcid("0");
                matchOrgan.setMatchid(enMatchId);
                matchOrgan.setOrganinfo("");
                matchOrgan.setOrgcode(buerEnterpriseDTO.getOrgcode());
                matchOrgan.setOrgname(buerEnterpriseDTO.getOrgname());
                matchOrgan.setPid(0L);
                matchOrgan.setSign("");
                matchOrgan.setSyscodeid(sysCodeId);
                matchOrgan.setType(1);
                matchOrganDao.save(matchOrgan);
            }
            
            for (BuyerOrganDetailDTO buyerOrganDetailDTO : buyerOrganDetailDTOs) {
                String matchId = buyerOrganDetailDTO.getMatchid();
                matchOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, matchId);

                //新增门店默认禁用（无论买家卖家），错误代码，但不得不加，加的很堵心
                //判断是否在别的平台店铺已审核通过
                //得到注册的平台信息
                AdminPlatform ap=adminPlatformService.getAPInfoBySyscodeId(sysCodeId);
                DealStatus.kacha();
                Shop existShop=shopService.findShopByMS(sysCodeId, matchId,ap.getPlatform());
                
                //分区新增门店信息      
                DealStatus.setShade( DealStatus.getShade());
                
                if(existShop!=null) {
                	disableFlag=false;
                }
                
                if (matchOrgan != null) {//update
                    matchOrgan = updateBuyerOrgan(matchOrgan, buyerOrganDetailDTO, sysCodeId,disableFlag);
                } else {//add
                    matchOrgan = saveBuyerOrgan(matchOrgan, buyerOrganDetailDTO, sysCodeId,disableFlag);
                }
               
                for (StoreDTO storeDTO : buyerOrganDetailDTO.getStore()) {
                    this.matchStore(storeDTO, sysCodeId, matchOrgan.getId());
                }

            }

        }
        return null;
    }

    private MatchOrgan saveBuyerOrgan(MatchOrgan matchOrgan, BuyerOrganDetailDTO buyerOrganDetailDTO, Long sysCodeId,boolean disabledFlag) throws Exception {
        matchOrgan = new MatchOrgan();
        BeanUtils.copyProperties(matchOrgan, buyerOrganDetailDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(buyerOrganDetailDTO.getSign())) {
            matchOrgan.setSign("");
        }
        matchOrgan.setMcid(buyerOrganDetailDTO.getMcid());
        matchOrgan.setSyscodeid(sysCodeId);
        matchOrgan.setDisabledflag(disabledFlag);
        MatchOrgan parentOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, buyerOrganDetailDTO.getParentid());
        if (parentOrgan != null) {
            matchOrgan.setPid(parentOrgan.getId());
        } else {
            matchOrgan.setPid(0L);
        }
        matchOrganDao.save(matchOrgan);

        List<AddressesDTO> addressesDTOList = buyerOrganDetailDTO.getAddresses();
        for (AddressesDTO addressesDTO : addressesDTOList) {
            Address address = new Address();
            BeanUtils.copyProperties(address, addressesDTO);
            address.setAddr(addressesDTO.getAddr());
            address.setName(addressesDTO.getLinkman());
            address.setSyscodeid(sysCodeId);
            address.setOrganid(matchOrgan.getId());
            address.setType(4);
            addressService.save(address);
        }

        //保存买家机构图片
        //this.saveOrganShopImg(buyerOrganDetailDTO.getImg(), matchOrgan.getId(), sysCodeId);

        return matchOrgan;
    }

    private MatchOrgan updateBuyerOrgan(MatchOrgan matchOrgan, BuyerOrganDetailDTO buyerOrganDetailDTO, Long sysCodeId,boolean disabledFlag) throws Exception {
        String matchId = buyerOrganDetailDTO.getMatchid();
        BeanUtils.copyProperties(matchOrgan, buyerOrganDetailDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(buyerOrganDetailDTO.getSign())) {
            matchOrgan.setSign("");
        }
        matchOrgan.setSyscodeid(sysCodeId);
        matchOrgan.setMcid(buyerOrganDetailDTO.getMcid());
        matchOrgan.setDisabledflag(disabledFlag);
        matchOrgan.setModifyDate(new Date());
        matchOrganDao.update(matchOrgan);

        matchOrganDao.deleteAddressByMatchId(matchId,sysCodeId);
        List<AddressesDTO> addressesDTOList = buyerOrganDetailDTO.getAddresses();
        for (AddressesDTO addressesDTO : addressesDTOList) {
            Address address = new Address();
            address.setArea(addressesDTO.getArea());
            address.setProvince(addressesDTO.getProvince());
            address.setCity(addressesDTO.getCity());
            address.setCountry(addressesDTO.getCountry());
            address.setAddr(addressesDTO.getAddr());
            address.setName(addressesDTO.getLinkman());
            address.setTel(addressesDTO.getTel());
            address.setSyscodeid(sysCodeId);
            address.setOrganid(matchOrgan.getId());
            address.setType(4);
            addressService.save(address);
        }

        //保存买家机构图片，先删后插
//		matchOrganDao.deleteOrganShopImgByMatchId(matchId);
//		this.saveOrganShopImg(buyerOrganDetailDTO.getImg(), matchOrgan.getId(), sysCodeId);

        return matchOrgan;
    }

    private void matchStore(StoreDTO storeDTO, Long sysCodeId, Long pId) throws Exception {
        String matchId = storeDTO.getMatchid();
        MatchOrgan store = matchOrganDao.getMatchOrganByMatchId(sysCodeId, matchId);

        if (store != null) {//update
            updateStore(store, storeDTO, sysCodeId, pId);
        } else {//add
            saveStore(store, storeDTO, sysCodeId, pId);
        }
    }

    private void saveStore(MatchOrgan store, StoreDTO StoreDTO, Long sysCodeId, Long pId) throws Exception {
        store = new MatchOrgan();
        BeanUtils.copyProperties(store, StoreDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(StoreDTO.getSign())) {
            store.setSign("");
        }
        store.setMcid("0");
        store.setSyscodeid(sysCodeId);
        store.setPid(pId);

        matchOrganDao.save(store);

    }

    private void updateStore(MatchOrgan store, StoreDTO StoreDTO, Long sysCodeId, Long pId) throws Exception {

        BeanUtils.copyProperties(store, StoreDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(StoreDTO.getSign())) {
            store.setSign("");
        }
        store.setMcid("0");
        store.setSyscodeid(sysCodeId);
        store.setPid(pId);
        matchOrganDao.update(store);


    }

    @Override
    public Map<String, Object> matchUser(BaseDTO<List<UserDTO>> baseDTO) throws Exception {
       
        Long sysCodeId = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
        List<UserDTO> UserDTOs = baseDTO.getData();

        for (UserDTO UserDTO : UserDTOs) {
           
            if (UserDTO.getOper() == 0) {//add              
               saveUser(UserDTO, sysCodeId);
                
            } else if (UserDTO.getOper() == 1) {//update
                
                updateUser(UserDTO, sysCodeId);
            } 
        }
      
        return null;
    }

    private void saveUser(UserDTO UserDTO, Long sysCodeId) throws Exception {
    	User user = new User();
        BeanUtils.copyProperties(user, UserDTO);

        //判断图片是否为空
        if (StringUtils.isBlank(UserDTO.getHeadimgurl())) {
            user.setHeadimgurl("");
        }
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(UserDTO.getSign())) {
            user.setSign("");
        }

        //生成密码
        String password =defaultPwd;
        PasswordBean pbean = new PasswordBean();
        Map<String, Object> pmap = pbean.newPassword(user.getTel(), password.toCharArray());
        user.setPassword((String) pmap.get(PasswordBean.MAP_KEY_NEWPWD));
        user.setMoflag(true);
        user.setDefsyscodeid(sysCodeId);
        userService.save(user);

        Long defOrganId = null;
        //存储员工与店铺的关系
        for (String organId : UserDTO.getOrganIds().split(",")) {
            MatchOrgan matchOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, organId);
            if (matchOrgan != null) {
                if (defOrganId == null && (matchOrgan.getType() == 2 || matchOrgan.getType() == 3)) {
                    defOrganId = matchOrgan.getId();
                }
                RelUserOrgan relUserOrgan = new RelUserOrgan();
                relUserOrgan.setOrganid(matchOrgan.getId());
                relUserOrgan.setUserid(user.getId());
                relUserOrgan.setSyscodeid(sysCodeId);
                relUserOrganService.save(relUserOrgan);
            }

        }
        if (defOrganId != null) {
            user.setOrganid(defOrganId);
            userService.update(user);

        }
        
        //增加用户和企业的关联,先删后插
        Long userId=user.getId();
        relUserCodeService.delRelUserCode(userId, sysCodeId);
        
        RelUserCode ruc=new RelUserCode();
        ruc.setUserid(userId);
        ruc.setSyscodeid(sysCodeId);
        relUserCodeService.save(ruc);
    }

    private void updateUser( UserDTO UserDTO, Long sysCodeId) throws Exception {
    	String matchId =UserDTO.getMatchid();
        User user=null;       
        
        List<User> userList= userService.findUserByMS( "'"+matchId+"'",sysCodeId);
       
        if(userList.size()>0) {
        	user=userList.get(0);
        }
        
        if(user!=null) {
	        BeanUtils.copyProperties(user, UserDTO);
	        //判断图片是否为空
	        if (StringUtils.isBlank(UserDTO.getHeadimgurl())) {
	            user.setHeadimgurl("");
	        }
	        //不是必须字段的sign的处理
	        if (StringUtils.isBlank(UserDTO.getSign())) {
	            user.setSign("");
	        }
	        user.setDefsyscodeid(sysCodeId);
	        user.setModifyDate(new Date());
	        userService.update(user);
	
	
	        Long defOrganId = null;
	        //删除已关联的机构，先删后插
	        matchOrganDao.deleteRelUserOrganByMatchId(matchId,sysCodeId);
	        
	        for (String organId : UserDTO.getOrganIds().split(",")) {
	            MatchOrgan matchOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, organId);
	            if (matchOrgan != null) {
	                if (defOrganId == null && (matchOrgan.getType() == 2 || matchOrgan.getType() == 3)) {
	                    defOrganId = matchOrgan.getId();
	                }
	                RelUserOrgan relUserOrgan = new RelUserOrgan();
	                relUserOrgan.setOrganid(matchOrgan.getId());
	                relUserOrgan.setUserid(user.getId());
	                relUserOrgan.setSyscodeid(sysCodeId);
	                relUserOrganService.save(relUserOrgan);
	            }
	
	        }
	        
	        //删除员工已不关联的仓库，即无用的仓库
	        matchOrganDao.deleteStoreBySyscodeId(sysCodeId);
	        
	        if (defOrganId != null) {
	            user.setOrganid(defOrganId);
	            userService.update(user);
	
	        }
        }
    }

//    private void deleteUser(UserDTO UserDTO, Long code) throws Exception {
//        String matchId = UserDTO.getMatchid();
//        matchOrganDao.deleteRelUserOrganByMatchId(matchId);
//        matchOrganDao.deleteUserByMatchId(matchId);
//
//    }

    @Override
    public Map<String, Object> matchSellerOrgan(BaseDTO<List<SellerOrganDTO>> baseDTO) throws Exception {
        Long sysCodeId = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
        List<SellerOrganDTO> sellerOrganDTOs = baseDTO.getData();

        for (SellerOrganDTO sellerOrganDTO : sellerOrganDTOs) {
            String matchId = sellerOrganDTO.getMatchid();
            MatchOrgan matchOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, matchId);

            //新增门店默认禁用（无论买家卖家）
            //判断是否在注册平台店铺已审核通过
            //得到注册的平台信息
            AdminPlatform ap=adminPlatformService.getAPInfoBySyscodeId(sysCodeId);
            DealStatus.kacha();
            Shop existShop=shopService.findShopByMS(sysCodeId, matchId,ap.getPlatform());
            
            //分区新增门店信息      
            DealStatus.setShade( DealStatus.getShade());

            if (matchOrgan != null) {//update
                matchOrgan = updateSellerOrgan(matchOrgan, sellerOrganDTO, sysCodeId,existShop);
            } else {//add
                matchOrgan = saveSellerOrgan(matchOrgan, sellerOrganDTO, sysCodeId,existShop);
            }

        }


        return null;
    }

    private MatchOrgan saveSellerOrgan(MatchOrgan matchOrgan, SellerOrganDTO sellerOrganDTO, Long sysCodeId,Shop existShop) throws Exception {
        matchOrgan = new MatchOrgan();
        BeanUtils.copyProperties(matchOrgan, sellerOrganDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(matchOrgan.getSign())) {
            matchOrgan.setSign("");
        }
        matchOrgan.setSyscodeid(sysCodeId);
        //判断是否在别的平台店铺已审核通过
        if(existShop!=null) {
        	matchOrgan.setDisabledflag(false);
        }else {
        	matchOrgan.setDisabledflag(true);
        }
        
        MatchOrgan parentOrgan = matchOrganDao.getMatchOrganByMatchId(sysCodeId, sellerOrganDTO.getParentid());
        if (parentOrgan != null) {
            matchOrgan.setPid(parentOrgan.getId());
        } else {
            matchOrgan.setPid(0L);
        }
        matchOrganDao.save(matchOrgan);

        Shop shop = new Shop();
        //判断是否在别的平台店铺已申请审核
        if(existShop!=null) {
        	shop.setDisabledflag(existShop.getDisabledflag());
        	shop.setOpendate(existShop.getOpendate());
        }else {
        	shop.setDisabledflag(true);
        }
        
        BeanUtils.copyProperties(shop, sellerOrganDTO);
        shop.setOrganid(matchOrgan.getId());
        shop.setName(sellerOrganDTO.getOrgname());
        shop.setSyscodeid(sysCodeId);
        shop.setMatchid(matchOrgan.getMatchid());
        shop.setHiddenflag(false);
        
        shopService.save(shop);

        //保存卖家机构图片
        this.saveOrganShopImg(sellerOrganDTO.getImg(), matchOrgan.getId(), sysCodeId,1);

        return matchOrgan;
    }

    private MatchOrgan updateSellerOrgan(MatchOrgan matchOrgan, SellerOrganDTO sellerOrganDTO, Long sysCodeId,Shop existShop) throws Exception {
  
        BeanUtils.copyProperties(matchOrgan, sellerOrganDTO);
        //不是必须字段的sign的处理
        if (StringUtils.isBlank(matchOrgan.getSign())) {
            matchOrgan.setSign("");
        }

        matchOrgan.setSyscodeid(sysCodeId);
//       matchOrgan.setPid(0L);
        matchOrgan.setModifyDate(new Date());
        
        //判断是否在别的平台店铺已申请审核
        if(existShop!=null) {
        	matchOrgan.setDisabledflag(false);
        }else {
        	matchOrgan.setDisabledflag(true);
        }
        
        matchOrganDao.update(matchOrgan);

        Shop shop = shopService.getShop(sysCodeId, matchOrgan.getId());
        if (shop == null) {
            shop = new Shop();
            BeanUtils.copyProperties(shop, sellerOrganDTO);
            shop.setOrganid(matchOrgan.getId());
            shop.setName(sellerOrganDTO.getOrgname());
            shop.setSyscodeid(sysCodeId);
            shop.setMatchid(matchOrgan.getMatchid());
            shop.setHiddenflag(false);
            
            //判断是否在别的平台店铺已审核通过
            if(existShop!=null) {
            	shop.setDisabledflag(existShop.getDisabledflag());
            	shop.setOpendate(existShop.getOpendate());
            }else {
            	shop.setDisabledflag(true);
            }
            
            shopService.save(shop);
        } else {
            BeanUtils.copyProperties(shop, sellerOrganDTO);
            shop.setOrganid(matchOrgan.getId());
            shop.setName(sellerOrganDTO.getOrgname());
            shop.setSyscodeid(sysCodeId);
            shop.setModifyDate(new Date());
            shop.setMatchid(matchOrgan.getMatchid());
            
            //判断是否在别的平台店铺已审核通过
            if(existShop!=null) {
            	shop.setDisabledflag(existShop.getDisabledflag());
            	shop.setOpendate(existShop.getOpendate());
            }else {
            	shop.setDisabledflag(true);
            }
            
            shopService.update(shop);
        }

        //更新卖家机构图片,先删后插
		matchOrganDao.deleteOrganShopImgByMatchId(matchOrgan.getMatchid(),sysCodeId);
		this.saveOrganShopImg(sellerOrganDTO.getImg(), matchOrgan.getId(), sysCodeId,1);

        return matchOrgan;
    }

    @Override
    public Long getMatchOrganIdBySM(Long sysCodeId, String matchId) {
        return matchOrganDao.checkOrganIsExist(matchId, sysCodeId);
    }

    /**
     * Count valid shop long.
     * admin-business使用，查询所有开通的店铺
     *
     * @return the long
     */
    public Long countValidOrgan() {
        return matchOrganDao.countValidOrgan();
    }

    /**
     * admin-business使用，根据id的list查询多个机构信息
     *
     * @return the long
     */
    @Override
    public List<Map<String, Object>> findOrganByIds(Map<String, List> para) {
        String sql = "select mo.syscodeid, mo.orgname from match_organ mo where mo.disabledflag = 1 and mo.pid = 0 and mo.syscodeid in ( #{ids} )";
        return matchOrganDao.query0(sql, para);
    }
    
    @Override
    public List<Map<String,Object>> findOrganByCategoryId(Long categoryId){
    	List<Map<String,Object>> mapList = shopService.query("select distinct(syscodeid) syscodeid from shop where disabledflag = 0 and opendate is not null");
    	if (mapList == null || mapList.size() <= 0) {
            return null;
        }
    	List<Object> codeList = new ArrayList<>();
    	for(Map<String,Object> map : mapList) {
    		codeList.add(map.get("syscodeid"));
    	}
    	Map<String, Object> filterMap = new HashMap<>();
    	filterMap.put("syscodeid", codeList);
    	List<MatchOrgan> organlist = this.selectByWhr0("type=1 and disabledflag = 0 and syscodeid in ( #{syscodeid} ) order by orgname", filterMap);
    	Map<String, Object> params = new HashMap<>();
    	params.put("categoryid", categoryId);
    	List<Map<String, Object>> imgList = organShopImgService.query0("select rsc.syscodeid,oi.imgurl,loi.imgurl logoimgurl from rel_shop_category rsc "
    			+ "left join organ_shop_img oi on rsc.organid = oi.organid and oi.imgtype=1 "
    			+ "left join organ_shop_img loi on rsc.organid = loi.organid and loi.imgtype=0 "
    			+ "where rsc.categoryid=#{categoryid}", params);
    	
    	List<Map<String, Object>> result = new ArrayList<>();
    	organlist.parallelStream().forEachOrdered((organ) -> {
    		Map<String, Object> map = new HashMap<>();
    		imgList.parallelStream().forEachOrdered((imgMap) -> {
    			if(Long.parseLong(imgMap.get("syscodeid").toString()) 
    					== organ.getSyscodeid().longValue()) {
    				map.put("syscodeid", imgMap.get("syscodeid").toString());
    				map.put("orgname", organ.getOrgname());
    				map.put("imgurl", imgMap.get("imgurl"));
    				map.put("logoimgurl", imgMap.get("logoimgurl"));
    				result.add(map);
    			}
    		});
    	});
    	
    	return result;
    }

    @Override
    public List<Map<String,Object>> findOrgan(SearchInfo searchInfo){
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String,Object>> mapList = shopService.query("select distinct(syscodeid) syscodeid from shop where disabledflag = 0 and opendate is not null");
        if (mapList == null || mapList.size() <= 0) {
            return result;
        }
        List<Object> codeList = new ArrayList<>();
        for(Map<String,Object> map : mapList) {
            codeList.add(map.get("syscodeid"));
        }
        Map<String, Object> filterMap = new HashMap<>();
        filterMap.put("syscodeid", codeList);
        List<MatchOrgan> organlist = this.selectByWhr0("type=1 and disabledflag = 0 and syscodeid in ( #{syscodeid} ) order by orgname", filterMap);

        List<Map<String, Object>> imgList = organShopImgService
                .query("select DISTINCT rsc.syscodeid,oi.imgurl,loi.imgurl logoimgurl from rel_shop_category rsc "
                + "left join organ_shop_img oi on rsc.organid = oi.organid and oi.imgtype=1 "
                + "left join organ_shop_img loi on rsc.organid = loi.organid and loi.imgtype=0 ");

        for (MatchOrgan organ : organlist) {
            Map<String, Object> map = new HashMap<>();
            for (Map<String, Object> imgMap : imgList) {
                if(Long.parseLong(imgMap.get("syscodeid").toString()) == organ.getSyscodeid().longValue()) {
                    map.put("syscodeid", imgMap.get("syscodeid").toString());
                    map.put("orgname", organ.getOrgname());
                    map.put("imgurl", imgMap.get("imgurl"));
                    map.put("logoimgurl", imgMap.get("logoimgurl"));
                    result.add(map);
                    if(searchInfo.getLength() != null && result.size() == searchInfo.getLength()){
                        return result;
                    }
                    break;
                }
            }
        }

        return result;
    }

}
